#!/usr/bin/env tsx

/**
 * 数据迁移脚本：从 JSON 文件迁移到 PostgreSQL
 * 
 * 使用方法：
 * 1. 确保已配置好 DATABASE_URL 环境变量
 * 2. 运行：npx tsx scripts/migrate-data.ts
 */

import { PrismaClient } from '@prisma/client'
import { readFileSync } from 'fs'
import { join } from 'path'

const prisma = new PrismaClient()

// 读取 JSON 数据文件
function readJsonFile(filename: string) {
  try {
    const filePath = join(process.cwd(), 'data', filename)
    const fileContent = readFileSync(filePath, 'utf-8')
    return JSON.parse(fileContent)
  } catch (error) {
    console.error(`读取文件 ${filename} 失败:`, error)
    return []
  }
}

async function migrateUsers() {
  console.log('🔄 开始迁移用户数据...')
  
  const users = readJsonFile('users.json')
  
  for (const user of users) {
    try {
      await prisma.user.upsert({
        where: { id: user.id },
        update: {
          email: user.email,
          name: user.name,
          avatar: user.avatar,
          role: user.role || 'USER',
          updatedAt: new Date(user.updatedAt || user.createdAt)
        },
        create: {
          id: user.id,
          email: user.email,
          name: user.name,
          avatar: user.avatar,
          role: user.role || 'USER',
          createdAt: new Date(user.createdAt),
          updatedAt: new Date(user.updatedAt || user.createdAt)
        }
      })
      console.log(`✅ 用户 ${user.name} (${user.email}) 迁移成功`)
    } catch (error) {
      console.error(`❌ 用户 ${user.email} 迁移失败:`, error)
    }
  }
  
  console.log(`✅ 用户数据迁移完成，共处理 ${users.length} 条记录\n`)
}

async function migrateCategories() {
  console.log('🔄 开始迁移分类数据...')
  
  const categories = readJsonFile('categories.json')
  
  for (const category of categories) {
    try {
      await prisma.category.upsert({
        where: { id: category.id },
        update: {
          name: category.name,
          description: category.description,
          icon: category.icon,
          updatedAt: new Date()
        },
        create: {
          id: category.id,
          name: category.name,
          description: category.description,
          icon: category.icon,
          createdAt: new Date(category.createdAt || new Date()),
          updatedAt: new Date()
        }
      })
      console.log(`✅ 分类 ${category.name} 迁移成功`)
    } catch (error) {
      console.error(`❌ 分类 ${category.name} 迁移失败:`, error)
    }
  }
  
  console.log(`✅ 分类数据迁移完成，共处理 ${categories.length} 条记录\n`)
}

async function migrateTools() {
  console.log('🔄 开始迁移工具数据...')
  
  const tools = readJsonFile('tools.json')
  
  for (const tool of tools) {
    try {
      await prisma.tool.upsert({
        where: { id: tool.id },
        update: {
          title: tool.title,
          description: tool.description,
          url: tool.url,
          image: tool.image,
          status: tool.status || 'PENDING',
          isDeployed: tool.isDeployed || false,
          deployPath: tool.deployPath,
          originalFile: tool.originalFile,
          categoryId: tool.categoryId,
          userId: tool.userId,
          updatedAt: new Date(tool.updatedAt || tool.createdAt)
        },
        create: {
          id: tool.id,
          title: tool.title,
          description: tool.description,
          url: tool.url,
          image: tool.image,
          status: tool.status || 'PENDING',
          isDeployed: tool.isDeployed || false,
          deployPath: tool.deployPath,
          originalFile: tool.originalFile,
          categoryId: tool.categoryId,
          userId: tool.userId,
          createdAt: new Date(tool.createdAt),
          updatedAt: new Date(tool.updatedAt || tool.createdAt)
        }
      })
      console.log(`✅ 工具 ${tool.title} 迁移成功`)
    } catch (error) {
      console.error(`❌ 工具 ${tool.title} 迁移失败:`, error)
    }
  }
  
  console.log(`✅ 工具数据迁移完成，共处理 ${tools.length} 条记录\n`)
}

async function migrateReviews() {
  console.log('🔄 开始迁移评价数据...')
  
  const reviews = readJsonFile('reviews.json')
  
  for (const review of reviews) {
    try {
      await prisma.review.upsert({
        where: { id: review.id },
        update: {
          rating: review.rating,
          comment: review.comment,
          toolId: review.toolId,
          userId: review.userId,
          updatedAt: new Date(review.updatedAt || review.createdAt)
        },
        create: {
          id: review.id,
          rating: review.rating,
          comment: review.comment,
          toolId: review.toolId,
          userId: review.userId,
          createdAt: new Date(review.createdAt),
          updatedAt: new Date(review.updatedAt || review.createdAt)
        }
      })
      console.log(`✅ 评价 ${review.id} 迁移成功`)
    } catch (error) {
      console.error(`❌ 评价 ${review.id} 迁移失败:`, error)
    }
  }
  
  console.log(`✅ 评价数据迁移完成，共处理 ${reviews.length} 条记录\n`)
}

async function migrateFavorites() {
  console.log('🔄 开始迁移收藏数据...')
  
  const favorites = readJsonFile('favorites.json')
  
  for (const favorite of favorites) {
    try {
      await prisma.favorite.upsert({
        where: { id: favorite.id },
        update: {
          toolId: favorite.toolId,
          userId: favorite.userId,
          updatedAt: new Date()
        },
        create: {
          id: favorite.id,
          toolId: favorite.toolId,
          userId: favorite.userId,
          createdAt: new Date(favorite.createdAt),
          updatedAt: new Date()
        }
      })
      console.log(`✅ 收藏 ${favorite.id} 迁移成功`)
    } catch (error) {
      console.error(`❌ 收藏 ${favorite.id} 迁移失败:`, error)
    }
  }
  
  console.log(`✅ 收藏数据迁移完成，共处理 ${favorites.length} 条记录\n`)
}

async function main() {
  console.log('🚀 开始数据迁移...\n')
  
  try {
    // 按依赖顺序迁移数据
    await migrateUsers()
    await migrateCategories()
    await migrateTools()
    await migrateReviews()
    await migrateFavorites()
    
    console.log('🎉 所有数据迁移完成！')
    
    // 显示迁移后的统计信息
    const stats = await Promise.all([
      prisma.user.count(),
      prisma.category.count(),
      prisma.tool.count(),
      prisma.review.count(),
      prisma.favorite.count()
    ])
    
    console.log('\n📊 迁移统计:')
    console.log(`- 用户: ${stats[0]} 条`)
    console.log(`- 分类: ${stats[1]} 条`)
    console.log(`- 工具: ${stats[2]} 条`)
    console.log(`- 评价: ${stats[3]} 条`)
    console.log(`- 收藏: ${stats[4]} 条`)
    
  } catch (error) {
    console.error('❌ 数据迁移失败:', error)
    process.exit(1)
  } finally {
    await prisma.$disconnect()
  }
}

// 运行迁移
main()
  .catch((error) => {
    console.error('❌ 迁移脚本执行失败:', error)
    process.exit(1)
  })
